package com.healthy_software.api;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.healthy_software.dto.HealthPlanDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class LLMClient {

    private final ObjectMapper mapper = new ObjectMapper();
    private final RestTemplate restTemplate = new RestTemplate();

    @Value("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")
    private String llmApiUrl;

    @Value("sk-7990cd6da2ff4daaa253329e355a52b2")
    private String llmApiKey;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public String queryLLM(String prompt) {
        try {
            // 构造 messages
            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", prompt);

            // 构造请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-plus"); // 或其他支持的模型名称
            requestBody.put("messages", List.of(userMessage));
            requestBody.put("temperature", 0.7);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(llmApiKey); // Authorization: Bearer token

            // 构造请求实体
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.postForEntity(llmApiUrl, request, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            } else {
                throw new RuntimeException("大模型API请求失败: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("调用大模型API失败", e);
        }
    }

//    public HealthAdviceResponse parseResponse(String json, Long goalId) {
//        try {
//            // Step 1: 解析外层结构
//            JsonNode root = mapper.readTree(json);
//            String content = root.path("choices").get(0).path("message").path("content").asText();
//
//            // Step 2: 清理 content 中可能带的 Markdown 格式（如 ```json）
//            content = content.replaceAll("(?s)```json\\s*", "")
//                    .replaceAll("(?s)```", "")
//                    .trim();
//
//            // Step 3: 将 JSON 解析成业务对象
//            HealthAdviceResponse res = mapper.readValue(content, HealthAdviceResponse.class);
//            res.setGoalId(goalId);
//            return res;
//
//        } catch (Exception e) {
//            throw new RuntimeException("解析大模型返回失败: " + e.getMessage(), e);
//        }
//    }
public HealthPlanDTO parseHealthPlanResponse(String llmResponse) {
    try {
        ObjectMapper mapper = new ObjectMapper();

        // 1. 解析最外层 JSON，提取 content
        JsonNode root = mapper.readTree(llmResponse);
        String content = root
                .path("choices")
                .get(0)
                .path("message")
                .path("content")
                .asText();

        // 2. 清理 Markdown 格式（去除 ```json ... ```）
        if (content.startsWith("```json")) {
            content = content.substring(7);  // 去掉开头 ```json
        }
        if (content.endsWith("```")) {
            content = content.substring(0, content.length() - 3);  // 去掉结尾 ```
        }

        // 3. 去掉首尾空白字符
        content = content.trim();

        // 4. 将提取出来的内容映射为 HealthPlanDTO
        return mapper.readValue(content, HealthPlanDTO.class);

    } catch (Exception e) {
        throw new RuntimeException("LLM响应解析失败", e);
    }
}

}
